<template>
    <div class="h-[380px]">
        <div class="flex justify-between">
            <div>
                <span class="mr-[26px] text-[16px] text-[#fff]">日期</span>
                <a-range-picker v-model:value="date" @change="getData" />
                <a-button :loading="loading" type="primary" class="ml-[26px] bg-[#53DCFF]"
                    @click="getData">查询</a-button>
            </div>
            <div class="flex items-center cursor-pointer" @click="exportData">
                <img src="@/assets/images/export_img.png" class="w-[110px] h-[37px]" />
                <!-- <span class="text-[16px] ml-[6px] text-[#53DCFF]">导出报告</span> -->
            </div>
        </div>
        <div class="w-[100%] mt-[20px]">
            <!-- <CustomTitle title="表金属杂质检测数据" /> -->
            <a-table id="tableRef" :scroll="{ y: 240, x: 1600 }" ref="tableRef" :loading="loading" class
                :pagination="false" :columns="columns" :data-source="tableData">
                <template #bodyCell="{ column, text }">
                    <template v-if="column.dataIndex === 'time'">{{ dayjs(text).format('YYYY-MM-DD HH:mm') }}</template>
                    <template v-if="column.dataIndex === 'pdf_num'">
                        <!-- <a target="blank" :href="'http://' + ip + ':' + port + '/PDF/' + text + '.pdf'">查看图谱</a> -->
                        <a target="blank" :href="`http://${ip}:${port}/PDF/${text}.pdf`">{{ text }}</a>
                    </template>
                </template>
            </a-table>
            <!-- <a-table ref="tableRef" :scroll="{ y: 200, x: '100%' }" :loading="loading" class :pagination="false" :columns="columns" :data-source="data"> </a-table> -->

            <div class="bg-[#1B1B1B] mt-[30px] w-full">
                <LineCharts width="1600" height="360" ref="lineChartsRef" />
            </div>
        </div>
    </div>
</template>
<script setup lang="ts">
import { apiGetHistoryByTag } from '@/http/api';
import dayjs, { Dayjs } from 'dayjs';
import { onBeforeMount, ref } from 'vue';
import * as echarts from 'echarts';
import * as XLSX from 'xlsx';
import FileSaver from 'file-saver';

// import { default_columns } from './columns';
const date = ref<any>([dayjs().subtract(6, 'day'), dayjs()]);
const lineChartsRef = ref();

const columns: any = ref([]);
const tableData = ref<any[]>([]);
const loading = ref(false);
const tableRef = ref('');
const ip = ref('');
const port = ref('');
const route = useRoute();
const times = ref<string[]>([]);
const downData: string[][] = [];
let measurement: string = '';
let sampling_pt: string = '';
let status: string = '';

const getData = async () => {
    tableData.value = [];
    times.value = [];
    columns.value = [];
    const res = {
        statement_id: 0,
        series: [
            {
                name: '',
                columns: ['time', 'CH4', 'CO', 'CO2', 'H2', 'N2', 'O2+Ar', 'point'],
                values: [
                    [1711934005000, 6, 4, 5, 70, 2, 3, '取样点1'],
                    [1711934014000, 6, 4, 5, 60, 2, 3, '取样点1'],
                ],
            },
        ],
    };
    try {
        loading.value = true;
        await apiGetHistoryByTag({
            start: dayjs((date.value[0] as Dayjs).format('YYYY-MM-DD 00:00:00')).toDate(),
            end: dayjs((date.value[1] as Dayjs).format('YYYY-MM-DD 23:59:59')).toDate(),
            analysis_project: measurement,
            sampling_pt: sampling_pt,
            status,
        });
    } catch (error) {
        if ((error as any).results) {
            const fliter_index: number[] = [];
            const datas1 = JSON.parse(JSON.stringify((error as any).results));
            // const datas = res.series;
            const datas = datas1[0].series;
            res.series[0].columns = datas[0].columns;
            res.series[0].columns.forEach((v, index) => {
                // if (v === 'status' || v === 'point' || v === 'pdf_num') {
                if (v === 'status' || v === 'point') {
                    fliter_index.push(index);
                } else {
                    columns.value.push({
                        title: v === 'time' ? '时间' : v === 'pdf_num' ? '图谱' : v,
                        dataIndex: v,
                        key: v,
                    });
                }
            });
            console.log(datas[0].values);

            res.series[0].values = datas
                ? datas[0].values.filter((_: any, i: number) => {
                    return !fliter_index.includes(i);
                })
                : [];

            res.series[0].values.forEach((v: any[]) => {
                times.value.push(dayjs(v[0]).format('YYYY-MM-DD HH:mm:ss'));

                tableData.value.push({
                    id: v[0],
                    ...Object.fromEntries(
                        v.map((item, index) => {
                            return [res.series[0].columns[index], item];
                        })
                    ),
                });
            });
            fillLineCharts();
            if (datas) {
                handleDownData(JSON.parse(JSON.stringify((error as any).results[0].series[0])));
            }
        }
    } finally {
        loading.value = false;
    }
};
const handleDownData = (datas: any) => {
    downData.splice(0, downData.length);
    const header = datas.columns.splice(0, datas.columns.length - 1);
    header[0] = '时间';
    downData.push(header);

    datas.values.forEach((v: any[]) => {
        // console.log('v:', v);
        v[0] = dayjs(v[0]).format('YYYY-MM-DD HH:mm:ss');

        downData.push(v.splice(0, v.length - 1));
    });
};
const fillLineCharts = () => {
    const option: echarts.EChartsOption = lineChartsRef.value.getOptions();
    let values: string[][] = [];
    const names: string[] = [];
    tableData.value.forEach((item, index) => {
        let v: string[] = [];
        for (const key in item) {
            if (Object.prototype.hasOwnProperty.call(item, key)) {
                const element = item[key];

                if (key !== 'id' && key !== 'time' && key !== 'point' && key !== 'undefined' && key !== 'status' && key !== 'pdf_num') {
                    v.push(element);
                    if (index === 0) {
                        names.push(key);
                    }
                }
            }
        }

        values.push(v);
    });
    values = values.reverse();

    (option.grid as any) = {
        top: '30%',
    };

    (option.title as any) = {
        text: `${measurement}  ${displaySamplingPt.value}`,
        textStyle: {
            color: '#fff',
        },
        left: 'center',
        top: '7%',
    };

    (option.legend as any)! = {
        textStyle: {
            color: '#fff',
        },
        data: names,
        top: '18%',
        right: '10%',
    };
    // (option.xAxis as any)!.data = times.value;
    (option.xAxis as any) = {
        data: times.value.reverse(),
        type: 'category',
        boundaryGap: false,
        axisLine: { onZero: false },
        axisLabel: {
            formatter: {
                day: '{d}日',
                hour: '{HH}:{mm}',
                millisecond: '{HH}:{mm}',
                minute: '{HH}:{mm}',
                month: '{M}月',
                none: '{HH}:{mm}',
                second: '{HH}:{mm}',
                year: '{yyyy}年',
            },
            show: true, // 显示刻度标签
        },
    };
    (option.dataZoom as any) = [
        {
            type: 'slider',
        },
        {
            type: 'inside',
        }
    ];
    const datas = names.map((v, i) => {
        return {
            name: v,
            type: 'line',
            // stack: 'Total',
            data: values.map(item => {
                return item[i];
            }),
        };
    });
    (option.series as any)! = datas;
    // (option.title as any)!.text = '异常';
    lineChartsRef.value.setOptions(option);
};

const exportData = () => {
    const workBook = XLSX.utils.book_new();
    // const ws1 = XLSX.utils.table_to_sheet(document.querySelector('#tableRef'));
    const ws1 = XLSX.utils.aoa_to_sheet(downData);
    XLSX.utils.book_append_sheet(workBook, ws1, '历史记录');
    const wbOut = XLSX.write(workBook, { bookType: 'xlsx', type: 'array', bookSST: true });
    try {
        FileSaver.saveAs(new Blob([wbOut], { type: 'application/octet-stream' }), '历史记录.xlsx');
    } catch (error) {
        console.log(error);
    }
};
defineExpose({
    refresh: getData,
});
const queryData = async () => {
    getData();
};
onBeforeMount(() => {
    const data = route.query;
    if (data) {
        measurement = data.measurement! as string;
        sampling_pt = data.sampling_pt! as string;
        status = (data.status! as string) || '';
        ip.value = data.ip! as string;
        port.value = data.port! as string;
    }
    console.log('measurement:', measurement);
    console.log('sampling_pt:', sampling_pt);

    queryData();
});
// 定义一个 computed 属性来显示你希望的名字
const displaySamplingPt = computed(() => {

    const samplingPtNames: { [key: string]: string } = {
        'NF3精馏组分分析取样点位1-预冷器进口': '预冷器出口',
        'NF3精馏组分分析取样点位2-预冷器出口': '精致(原料气)',
        'NF3精馏组分分析取样点位3-预冷器塔釜': '预冷器塔釜',
        'NF3精馏组分分析取样点位4-精馏低沸塔1出口': '预留',
        'NF3精馏组分分析取样点位9-精馏高沸塔3塔釜取样': '塔3塔釜',
        'NF3精制组分分析取样点位1-吸附剂吸附后': '塔2出口',
        'NF3精制组分分析取样点位2-吸附剂吸附后': '塔1出口',
        // 根据实际需要添加更多映射
    };
    return samplingPtNames[measurement + sampling_pt] || sampling_pt;
});

</script>
<style lang="scss" scoped></style>
